package com.db.exchange;

import com.db.protocol.ExchangeProtocol;
import com.db.protocol.ReportFixProtocol;
import com.db.protocol.message.ReportMessage;
import com.db.protocol.tags.OrderSide;
import com.db.transport.SessionFactory;
import com.db.transport.client.SessionClient;
import com.db.transport.exchange.SessionExchange;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Logger;

/**
 *
 * @author nulls.narik
 */
public class Exchange {

    private static Logger logger = Logger.getLogger(Exchange.class.getName());

    public String getExchangeID() {
        return exchangeID;
    }

    private final String exchangeID;
    private Thread threadSession;
    private SessionExchange session;

    public Exchange(String exchangeID) {
        this.exchangeID = exchangeID;
    }

    public void connect(InetAddress address, int port) {
        try {
            session = SessionFactory.getSessionExchange(exchangeID, address, port);
            threadSession = new Thread(session);
            threadSession.start();
            session.sendMessage(exchangeID);
            logger.info(String.format("Exchange [%s]: start transport part", exchangeID));
        } catch (IOException e) {
            logger.warning(String.format("Exchange [%s]: error create transport part", exchangeID));
        }
    }

    public void sendReport(String clientID, String stockName, OrderSide side, Integer quantity, Float price) {
        ReportMessage message = new ReportMessage(clientID, stockName, side, quantity, price, exchangeID);
        session.sendMessage(message.toString());
    }

    public void sendMessage(String message) {
        session.sendMessage(message);
    }
}
